// 定义地址为常量
const BASE_URL = 'http://43.138.15.137:7000/api/private/v1'
class Index {
  constructor(container) {
    this.container = document.querySelector(container)

    if (!this.container) {
      // console.error('未找到容器元素:', container);
      return;
    }
    this.formText = this.container.querySelector('input[type=text]')
    this.formPassword = this.container.querySelector('input[type=password]')
    this.loginButton = this.container.querySelector('button[type=submit]')
    this.resetButton = this.container.querySelector('button[type=reset]')
    this.interfacePath = 'http://43.138.15.137:7000/api/private/v1/login'
    // 本地存储
    this.localStorage()
    // 点击事件
    this.clickEvent()
  }
  localStorage(tokenValue) {
    localStorage.setItem('token', tokenValue)
  }
  clickEvent() {
    this.loginButton.addEventListener('click', (e) => {
      //  ajax
      let loginParams = {
        username: this.formText.value,
        password: this.formPassword.value
      }
      let ajax = new Ajax()
      ajax.post(this.interfacePath, loginParams, (res) => {
        let resObj = JSON.parse(res)
        console.log(resObj);
        let status = resObj.meta.status
        let msg = resObj.meta.msg
        console.log(status, msg);
        if (status == 200) {
          const dateToken = resObj.data.token
          this.localStorage(dateToken)
          new Message('success', '登录成功').show()

          setTimeout(() => {
            window.location.href = '../html/manage2.html';
          }, 3000);
        } else if (status == 400) {
          new Message('danger', msg).show()
        } else {
          this.localStorage('')
        }
      })

    })
  }
}
let index = new Index('#index')
class Ajax {
  constructor() {
    this.xhr = new XMLHttpRequest();
  }

  /**
   * 发送 GET 请求
   * @param {string} url - 请求的 URL
   * @param {Function} callback - 请求成功后的回调函数
   */
  get(url, callback, headers) {
    this.xhr.open('GET', url, true);
    this.xhr.setRequestHeader('Authorization', headers);
    this.xhr.onreadystatechange = () => {
      if (this.xhr.readyState === 4 && this.xhr.status === 200) {
        callback(this.xhr.responseText);
      }
    };
    this.xhr.send();
  }

  /**
   * 发送 POST 请求
   * @param {string} url - 请求的 URL
   * @param {Object} data - 需要发送的数据
   * @param {Function} callback - 请求成功后的回调函数
   */
  post(url, data, callback) {
    this.xhr.open('POST', url, true);
    this.xhr.setRequestHeader('Content-type', 'application/json');
    this.xhr.onreadystatechange = () => {
      if (this.xhr.readyState === 4 && this.xhr.status === 200) {
        callback(this.xhr.responseText);
      }
    };
    this.xhr.send(JSON.stringify(data));
  }
  config() {

  }
}
class Message {
  constructor(type, msg) {
    this.type = type
    this.msg = msg
  }
  show() {
    let msgBox = document.createElement('div')
    msgBox.classList.add('msg-box')
    msgBox.classList.add(this.type)
    msgBox.innerHTML = this.msg
    document.body.appendChild(msgBox)
    setTimeout(() => {
      msgBox.style.animation = 'msg-box-hide 0.5s forwards'
      msgBox.addEventListener('animationend', () => {
        document.body.removeChild(msgBox)
      })
    }, 2000)
  }
}
// 继承
class IndexManage extends Index {
  constructor(container) {
    super()
    this.menuData = null
    this.manageContainer = document.querySelector(container)
    this.init()

  }
  async init() {
    try {
      this.menuData = await this.fetchMenuData()
      this.getMenuData()
    } catch (error) {
      // console.error('Failed to load menu data:', error)
    }
  }
  fetchMenuData() {
    return new Promise((resolve, reject) => {
      let manageAjax = new Ajax()
      manageAjax.get(BASE_URL + '/menus', (res) => {
        resolve(JSON.parse(res))
      }, localStorage.getItem('token'))
    })
  }
  getMenuData() {
    const menuData = this.menuData.data;
    const container = document.querySelector('.caidan');
    menuData.forEach(item => {
      // 创建外层盒子
      // console.log(item);
      const box = document.createElement('div');
      box.className = 'col-md-12 xmy_center_left_box hezi';
      // 创建主菜单项
      const ul = document.createElement('ul');
      ul.innerHTML = `
        <li><span class="iconfont icon-shuju1"></span></li>
        <li><p>${item.authName}</p></li>
        <li><i></i></li>
      `;
      ul.classList.add('xmy_center_left_box1');
      // 创建子菜单容器
      if (item.children && item.children.length > 0) {
        const subBox = document.createElement('div');
        subBox.className = 'col-md-12 xmy_center_left_box2 hezi';
        item.children.forEach(subItem => {
          const subUl = document.createElement('ul');
          subUl.innerHTML = `
            <li><span class="iconfont icon-shuju"></span></li>
            <li><p>${subItem.authName}</p></li>
            <li><i></i></li>
          `;
          subBox.classList.add('xmy_center_left_box3');
          subBox.appendChild(subUl);
        });
        box.appendChild(ul);
        box.appendChild(subBox);
        // 点击主菜单项时切换子菜单的显示状态
        ul.addEventListener('click', () => {
          subBox.classList.toggle('show');
        });
      } else {
        box.appendChild(ul);
      }

      container.appendChild(box);

    });
    const xmyCenterLeftBox1 = document.querySelectorAll('.xmy_center_left_box1');
    const xmyCenterLeftBox3 = document.querySelectorAll('.xmy_center_left_box3');
    xmyCenterLeftBox1.forEach((item, index) => {
      item.addEventListener('click', () => {
        if (xmyCenterLeftBox3[index].style.height === '0px') {
          xmyCenterLeftBox3[index].style.height = '40px'
        } else {
          xmyCenterLeftBox3[index].style.height = '0px'
        }
      });
    })


    const menuButton = document.querySelector('.xmy_center_left_top');
    const xmyCenterLeft = document.querySelector('.xmy_center_left');
    const xmyCenterRight = document.querySelector('.xmy_center_right');
    const iframe = document.querySelector('iframe');


    menuButton.addEventListener('click', () => {
      if (xmyCenterLeft.className == 'xmy_center_left col-md-1') {
        xmyCenterLeft.className = 'xmy_center_left col-md-2'
        xmyCenterRight.className = 'xmy_center_right col-md-10'
        // 加上里面的文字和箭头
        const liElements1 = document.querySelectorAll('.xmy_center_left_box ul li p');
        const iElements2 = document.querySelectorAll('.xmy_center_left_box ul li i');
        const liElements = document.querySelectorAll('.xmy_center_left_box2 ul li p');
        const iElements = document.querySelectorAll('.xmy_center_left_box2 ul li i');
        liElements.forEach(li => {
          li.style.display = 'block';
        });
        iElements.forEach(i => {
          i.style.display = 'block';
        });
        liElements1.forEach(li => {
          li.style.display = 'block';
        })
        iElements2.forEach(i => {
          i.style.display = 'block';
        })
      }
      else {
        xmyCenterLeft.className = 'xmy_center_left col-md-1'
        xmyCenterRight.className = 'xmy_center_right col-md-11'
        // 去掉里面的文字和箭头只留着图标
        const liElements1 = document.querySelectorAll('.xmy_center_left_box ul li p');
        const iElements2 = document.querySelectorAll('.xmy_center_left_box ul li i');
        const liElements = document.querySelectorAll('.xmy_center_left_box2 ul li p');
        const iElements = document.querySelectorAll('.xmy_center_left_box2 ul li i');
        liElements.forEach(li => {
          li.style.display = 'none';
        });
        iElements.forEach(i => {
          i.style.display = 'none';
        });
        liElements1.forEach(li => {
          li.style.display = 'none';
        }
        );
        iElements2.forEach(i => {
          i.style.display = 'none';
        })
      }
    });
    xmyCenterLeftBox3[0].addEventListener('click', () => {
      xmyCenterRight.style.display = 'none'
      iframe.style.display = 'block'
    })
  }
}
let indexManage = new IndexManage('#manage2')
// 自定义提示
function customAlert(type, msg) {
  let wyfAlert = document.querySelector('.wyf-alert')
  wyfAlert.classList.add(type, 'wyf-alert-show')
  wyfAlert.innerHTML = msg
  setTimeout(() => {
    wyfAlert.classList.remove(type, 'wyf-alert-show')
    wyfAlert.innerHTML = ''
  }, 1000)
}